<template>
  <div class="app-container">
    <div style="flex: 1;min-width: 400px;">
      <div style="margin-bottom: 4px;">
        <el-button type="primary" size="mini" @click="handleAdd('type')">新增</el-button>
      </div>
      <el-tree
        ref="tree"
        :data="treeList"
        show-checkbox
        node-key="id"
        default-expand-all
        @node-click="nodeClick"
        @check="checkChange">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        【{{data.dictCode}}】
        <span class="custom-tree-span">{{ data.dictName }}</span>
        <span style="float: right; padding-right: 10px;">
          <el-button
            type="text"
            size="mini"
            @click="() => handleEdit(0, data)">
            编辑
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
      </el-tree>
    </div>

    <div style="flex: 4;margin-left: 10px;">
      <div style="margin-bottom: 4px;">
        <el-button type="primary" size="mini" @click="handleAdd('item')">新增</el-button>
        <el-button type="danger" size="mini" @click="handleDeleteAll()">删除</el-button>
      </div>
      <el-table ref="multipleTable" :data="list" v-loading="listLoading" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column label="编码">
          <template slot-scope="scope">
            {{scope.row.dictCode}}
          </template>
        </el-table-column>
        <el-table-column label="名称">
          <template slot-scope="scope">
            <span>{{scope.row.dictName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            <span>{{scope.row.remark}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 4px;">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :page-size="pageSize"
          :current-page="pageNum"
          :total="pageTotal"
          @current-change="pageChange">
        </el-pagination>
      </div>
    </div>

    <el-dialog :title="dialogFormTitle" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="编号" :label-width="formLabelWidth">
          <el-input v-model="form.dictCode" :disabled="codeDisabled"></el-input>
        </el-form-item>
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="form.dictName"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { dictApi } from '@/api/dict'

  export default {
    data() {
      return {
        pageNum: 1, // 当前页
        pageSize: 20, // 每页数
        pageTotal: 0, // 总页数
        list: null,
        listLoading: true,
        dialogFormVisible: false,
        dialogFormTitle: '',
        formLabelWidth: '100px',
        form: {},
        oldForm: {},
        codeDisabled: true,
        dialogPermissionVisible: false,
        dictId: '',
        dictName: '',
        treeList: null,
        clickTreeBtn: false
      }
    },
    filters: {
    },
    created() {
      this.fetchData()
    },
    methods: {
      fetchData() {
        dictApi.listDictType({ pid: 0 }).then(response => {
          console.log(response)
          this.treeList = response.data
          if (response.data.length > 0 && this.dictId === '') {
            this.dictId = response.data[0].id
            this.$refs.tree.setCheckedKeys([this.dictId])
            this.dictName = response.data[0].dictName
            this.fetchItem()
          }
        })
      },
      fetchItem() {
        this.listLoading = true
        dictApi.listDictItem(this.pageNum, this.pageSize, this.dictId).then(response => {
          this.list = response.list
          setTimeout(() => { this.listLoading = false }, 1000)
          // this.listLoading = false
          this.pageTotal = response.total
          this.pageNum = response.pageNum
        })
      },
      handleAdd(type) {
        this.dialogFormTitle = '新增类型'
        let pid = 0
        if (type === 'item') {
          pid = this.dictId
          this.dialogFormTitle = '新增子项 -- 类型：' + this.dictName
        }
        this.form = {
          pid: pid
        }
        this.codeDisabled = false
        this.dialogFormVisible = true
      },
      handleDeleteAll() {
        console.log(this.$refs.multipleTable.selection)
        const selectedData = this.$refs.multipleTable.selection
        if (selectedData.length <= 0) {
          this.$message({
            type: 'info',
            message: '请选择至少一行数据'
          })
          return
        }
        let ids = ''
        for (let i = 0; i < selectedData.length; i++) {
          ids += selectedData[i].id + ','
        }
        if (ids.length > 0) {
          ids = ids.substring(0, ids.length - 1)
        }
        this.$confirm('确认删除选中的' + selectedData.length + '条数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          dictApi.deleteDictItem(ids).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.fetchItem()
          })
        })
      },
      handleEdit(index, row) {
        console.log('handleEdit')
        this.clickTreeBtn = true
        this.oldForm = {
          id: row.id,
          dictCode: row.dictCode,
          dictName: row.dictName,
          remark: row.remark
        }
        this.form = row
        this.codeDisabled = true
        this.dialogFormTitle = '编辑'
        this.dialogFormVisible = true
      },
      handleDelete(index, row) {
        this.$confirm('确认删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          dictApi.deleteDictItem(row.id + '').then(response => {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.fetchItem()
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        })
      },
      submit() {
        console.log(this.form)
        if (this.form.id && this.form.id !== '') {
          // 编辑
          dictApi.updateDict(this.form).then(response => {
            this.dialogFormVisible = false
          })
        } else {
          // 新增
          dictApi.addDict(this.form).then(response => {
            this.dialogFormVisible = false
            if (this.form.pid === 0) {
              this.fetchData()
            } else {
              this.fetchItem()
            }
          })
        }
      },
      cancelSubmit() {
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].id === this.oldForm.id) {
            this.list[i].dictCode = this.oldForm.dictCode
            this.list[i].dictName = this.oldForm.dictName
            this.list[i].remark = this.oldForm.remark
          }
        }
        for (let i = 0; i < this.treeList.length; i++) {
          if (this.treeList[i].id === this.oldForm.id) {
            this.treeList[i].dictCode = this.oldForm.dictCode
            this.treeList[i].dictName = this.oldForm.dictName
            this.treeList[i].remark = this.oldForm.remark
          }
        }
        this.dialogFormVisible = false
      },
      remove(node, data) {
        this.clickTreeBtn = true
        this.$confirm('确认删除字典类型，其子项也将被删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          dictApi.deleteDictType(data.id).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            if (data.id === this.dictId) {
              this.dictId = ''
            }
            this.fetchData()
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        })
      },
      pageChange(val) {
        this.pageNum = val
        this.fetchItem()
      },
      nodeClick(data, node, obj) {
        if (this.clickTreeBtn) {
          this.clickTreeBtn = false
          return
        }
        // alert(data.dictName)
        // this.$refs.tree.setCheckedKeys([])
        this.$refs.tree.setCheckedKeys([data.id])
        this.pageNum = 1
        this.dictId = data.id
        this.dictName = data.dictName
        this.fetchItem()
      },
      checkChange(data, checkedData) {
        // tree的复选框实现单选
        this.$refs.tree.setCheckedKeys([data.id])
        this.pageNum = 1
        this.dictId = data.id
        this.dictName = data.dictName
        this.fetchItem()
      }
    }
  }
</script>

<style scoped>
  .app-container {
    display: flex;
  }
  .custom-tree-node {
    width: 100%;
  }
  .custom-tree-span {
    height: 28px;
    display: inline-block;
    padding-top: 4px;
  }
</style>
